<template>
  <div class="apple-style-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">主机出租订单</h1>
    </div>

    <!-- 查询条件区域 -->
    <el-card class="filter-card apple-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.order_number" placeholder="请输入订单号" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.customer_name" placeholder="请输入客户名称" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="网站域名">
          <el-input v-model="queryParams.domain_name" placeholder="请输入网站域名" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="对接人">
          <el-input v-model="queryParams.nickname" placeholder="请输入对接人" clearable class="apple-input" />
        </el-form-item>
        <el-form-item label="生效日期">
          <el-date-picker
            v-model="dateRange.effective_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item label="截至日期">
          <el-date-picker
            v-model="dateRange.expiry_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            class="apple-date-picker"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" class="apple-button primary-button">点击查询</el-button>
          <el-button @click="resetQuery" class="apple-button">重置查询条件</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表区域 -->
    <el-card class="table-card apple-card">
      <div class="table-header">
        <div class="left-buttons">
          <el-button type="primary" @click="handleAdd" class="apple-button primary-button">
            <el-icon><Plus /></el-icon> 添加
          </el-button>
          <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete" class="apple-button danger-button" v-if="hasDeletePermission">
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="success" @click="handleExport" :loading="exportLoading" class="apple-button success-button">
            <el-icon><Download /></el-icon> {{ isFiltered ? '导出筛选数据' : '导出全部数据' }}
          </el-button>
          <el-button type="primary" @click="handleImportTemplate" class="apple-button primary-button" v-if="hasEditPermission">
            <el-icon><Upload /></el-icon> 导入
          </el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="hostOrderList"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        class="apple-table"
      >
        <el-table-column type="selection" width="45" />
        <el-table-column label="操作" width="150" fixed="left">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)" class="apple-link-button" v-if="hasEditPermission">编辑</el-button>
            <el-button type="primary" link @click="handleView(scope.row)" class="apple-link-button">查看</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)" class="apple-link-button" v-if="hasDeletePermission">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="order_number" label="订单号" min-width="130" />
        <el-table-column prop="customer_display" label="客户名称" min-width="120" />
        <el-table-column prop="order_amount" label="订单金额" min-width="90" sortable />
        <el-table-column prop="rental_years" label="出租年限" min-width="90" sortable />
        <el-table-column prop="domain_name" label="网站域名" min-width="140" />
        <el-table-column prop="effective_date" label="生效日期" min-width="100" sortable />
        <el-table-column prop="expiry_date" label="截至日期" min-width="100" sortable />
        <el-table-column prop="nickname_display" label="对接人" min-width="90" />
        <el-table-column prop="order_remarks" label="订单备注" min-width="140" show-overflow-tooltip />
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="apple-pagination"
        />
      </div>
    </el-card>

    <!-- 添加/编辑订单弹窗 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      class="apple-dialog"
    >
      <el-form
        ref="hostOrderFormRef"
        :model="hostOrderForm"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户" prop="customer">
              <div class="customer-select-wrapper">
                <el-select
                  v-model="hostOrderForm.customer"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入客户名称"
                  :remote-method="remoteCustomerSearch"
                  :loading="customerLoading"
                  style="width: 100%"
                  @change="handleCustomerSelectChange"
                  class="apple-select"
                >
                  <el-option
                    v-for="item in customerOptions"
                    :key="item.id"
                    :label="item.customer_name"
                    :value="item.id"
                  />
                  <el-option
                    v-if="searchCustomerKeyword && showCreateOption"
                    :value="'create_new'"
                    :label="`创建新客户: ${searchCustomerKeyword}`"
                  />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单号" prop="order_number">
              <el-input v-model="hostOrderForm.order_number" placeholder="请输入订单号" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出租年限" prop="rental_years">
              <el-input-number v-model="hostOrderForm.rental_years" :min="1" :max="10" style="width: 100%" class="apple-input-number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单金额" prop="order_amount">
              <el-input v-model.number="hostOrderForm.order_amount" placeholder="请输入金额" class="apple-input">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单来源" prop="order_source">
              <el-select v-model="hostOrderForm.order_source" placeholder="请选择来源" style="width: 100%" class="apple-select">
                <el-option :value="0" label="Newbe工作室" />
                <el-option :value="1" label="纽币德信息科技" />
                <el-option :value="2" label="官方网站" />
                <el-option :value="3" label="其它" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="对接人" prop="nickname">
              <el-select v-model="hostOrderForm.nickname" placeholder="请选择对接人" style="width: 100%" class="apple-select">
                <el-option
                  v-for="item in userOptions"
                  :key="item.id"
                  :label="item.nickname"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="网站域名" prop="domain_name">
          <el-input v-model="hostOrderForm.domain_name" placeholder="请输入域名或IP地址" class="apple-input" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效日期" prop="effective_date">
              <el-date-picker v-model="hostOrderForm.effective_date" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" class="apple-date-picker" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截至日期" prop="expiry_date">
              <el-date-picker v-model="hostOrderForm.expiry_date" type="date" placeholder="选择日期" style="width: 100%" value-format="YYYY-MM-DD" class="apple-date-picker" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="hostOrderForm.email" placeholder="请输入电子邮箱" class="apple-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="hostOrderForm.mobile" placeholder="请输入手机号码" class="apple-input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="客户微信" prop="customer_wechat">
          <el-input v-model="hostOrderForm.customer_wechat" placeholder="请输入客户微信" class="apple-input" />
        </el-form-item>

        <el-form-item label="订单备注" prop="order_remarks">
          <el-input v-model="hostOrderForm.order_remarks" type="textarea" :rows="3" placeholder="请输入备注信息" class="apple-textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="apple-button">取消</el-button>
          <el-button type="primary" @click="submitForm" class="apple-button primary-button">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看订单详情弹窗 -->
    <el-dialog
      title="主机出租订单详情"
      v-model="viewDialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      class="apple-dialog"
    >
      <el-descriptions :column="2" border class="apple-descriptions">
        <el-descriptions-item label="订单号">{{ detailData.order_number }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailData.customer_display }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">{{ detailData.order_amount }} 元</el-descriptions-item>
        <el-descriptions-item label="出租年限">{{ detailData.rental_years }} 年</el-descriptions-item>
        <el-descriptions-item label="订单来源">{{ detailData.order_source_display }}</el-descriptions-item>
        <el-descriptions-item label="对接人">{{ detailData.nickname_display }}</el-descriptions-item>
        <el-descriptions-item label="网站域名" :span="2">{{ detailData.domain_name }}</el-descriptions-item>
        <el-descriptions-item label="生效日期">{{ detailData.effective_date }}</el-descriptions-item>
        <el-descriptions-item label="截至日期">{{ detailData.expiry_date }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ detailData.email }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ detailData.mobile }}</el-descriptions-item>
        <el-descriptions-item label="客户微信">{{ detailData.customer_wechat }}</el-descriptions-item>
        <el-descriptions-item label="创建日期">{{ detailData.creation_date }}</el-descriptions-item>
        <el-descriptions-item label="订单备注" :span="2">{{ detailData.order_remarks }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入模板弹窗 -->
    <el-dialog
      title="导入主机出租订单"
      v-model="importDialogVisible"
      width="850px"
      append-to-body
      destroy-on-close
      class="apple-dialog"
    >
      <el-form
        ref="importFormRef"
        :model="importForm"
        :rules="importRules"
        label-width="100px"
      >
        <el-form-item label="选择文件" prop="file">
          <el-upload
            v-model:file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :before-upload="beforeFileUpload"
            :on-exceed="handleFileExceed"
            :limit="1"
            accept=".xlsx,.xls,.csv"
            class="apple-upload"
          >
            <el-button type="primary" :icon="UploadFilled">选择文件</el-button>
          </el-upload>
          
          <!-- 添加下载导入模板链接 -->
          <div class="upload-tip">
            <p>请确保Excel表头包含：订单号、客户名称、订单金额、出租年限、网站域名、生效日期、截至日期等字段</p>
          </div>
        </el-form-item>
      
        <!-- 添加模板表格 -->
        <div class="template-table-container">
          <h4>导入模板格式参考（可直接复制到Excel）：</h4>
          <div class="template-instruction">
            <p>1. 请复制以下内容到Excel中</p>
            <p>2. 按照示例格式添加您的数据</p>
            <p>3. 保存为Excel格式后上传</p>
          </div>
          <div class="copy-button-container">
            <el-button type="primary" size="small" @click="copyTemplateToClipboard">
              <el-icon><DocumentCopy /></el-icon> 复制表格内容
            </el-button>
            <el-button type="success" size="small" @click="downloadExcelTemplate">
              <el-icon><Download /></el-icon> 下载Excel模板
        </el-button>
      </div>
          <div class="scrollable-table">
            <table class="template-table" ref="templateTable">
              <thead>
                <tr>
                  <th>订单号*</th>
                  <th>客户名称*</th>
                  <th>订单金额*</th>
                  <th>出租年限*</th>
                  <th>订单来源*</th>
                  <th>网站域名*</th>
                  <th>电子邮箱</th>
                  <th>手机号码</th>
                  <th>客户微信</th>
                  <th>生效日期*</th>
                  <th>截至日期*</th>
                  <th>对接人</th>
                  <th>订单备注</th>
                </tr>
              </thead>
              <tbody>
                <tr>
                  <td>ORD202401001</td>
                  <td>示例客户</td>
                  <td>1999.99</td>
                  <td>1</td>
                  <td>0</td>
                  <td>example.com</td>
                  <td>customer@example.com</td>
                  <td>13800138000</td>
                  <td>exampleuser</td>
                  <td>2023-01-01</td>
                  <td>2024-01-01</td>
                  <td>张三</td>
                  <td>示例订单备注信息</td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="template-notes">
            <p><strong>说明：</strong></p>
            <p>* 标记为必填字段</p>
            <p>订单来源：0=Newbe工作室、1=纽币德信息科技、2=官方网站、3=其它</p>
            <p>出租年限：填写阿拉伯数字(如1、2、3等)</p>
            <p>日期格式：YYYY-MM-DD (如2023-01-01)</p>
          </div>
        </div>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false" class="apple-button">取消</el-button>
          <el-button type="primary" @click="submitImport" :loading="importLoading" class="apple-button primary-button">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete, Download, Upload, UploadFilled, DocumentCopy } from '@element-plus/icons-vue';
import { 
  getHostOrderList, 
  getHostOrder, 
  createHostOrder, 
  updateHostOrder, 
  deleteHostOrder, 
  batchDeleteHostOrders, 
  exportHostOrders,
  importRentals,
  downloadImportTemplate
} from '@/api/host-order';
import { getCustomerList, createCustomer, getCustomer } from '@/api/customers';
import { getUserList } from '@/api/users';
import { useRouter, useRoute } from 'vue-router';
import { canEdit, canDelete } from '@/utils/permissions';

// 新增 router 和 route
const router = useRouter();
const route = useRoute();

// 计算属性：是否可以编辑
const hasEditPermission = computed(() => {
  return canEdit(route.path);
});

// 计算属性：是否可以删除
const hasDeletePermission = computed(() => {
  return canDelete(route.path);
});

// 查询参数
const queryParams = reactive({
  order_number: '',
  customer_name: '',
  domain_name: '',
  nickname: ''
});

// 日期范围
const dateRange = reactive({
  effective_date: [],
  expiry_date: []
});

// 表格数据
const loading = ref(false);
const hostOrderList = ref([]);
const selectedIds = ref([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('添加主机出租订单');
const dialogType = ref('add'); // add 或 edit
const viewDialogVisible = ref(false);
const detailData = ref({});
const importDialogVisible = ref(false);
const fileList = ref([]);
const selectedFile = ref(null);
const importLoading = ref(false);
const importFormRef = ref(null);
const importForm = reactive({
  file: null
});
const importRules = {
  file: [{ required: true, message: '请选择要导入的文件', trigger: 'change' }]
};

// 表单对象
const hostOrderFormRef = ref(null);
const hostOrderForm = reactive({
  id: undefined,
  customer: '',
  order_number: '',
  rental_years: 1,
  order_amount: '',
  order_source: 0,
  domain_name: '',
  email: '',
  mobile: '',
  customer_wechat: '',
  effective_date: '',
  expiry_date: '',
  nickname: '',
  order_remarks: ''
});

// 表单验证规则
const rules = {
  customer: [{ required: true, message: '请选择客户', trigger: 'change' }],
  order_number: [{ required: true, message: '请输入订单号', trigger: 'blur' }],
  rental_years: [{ required: true, message: '请输入出租年限', trigger: 'blur' }],
  order_amount: [
    { required: true, message: '请输入订单金额', trigger: 'blur' },
    { type: 'number', message: '金额必须为数字', trigger: 'blur' }
  ],
  domain_name: [{ required: true, message: '请输入网站域名', trigger: 'blur' }],
  effective_date: [{ required: true, message: '请选择生效日期', trigger: 'change' }],
  expiry_date: [{ required: true, message: '请选择截至日期', trigger: 'change' }],
  email: [{ type: 'email', message: '请输入正确的电子邮箱格式', trigger: 'blur' }]
};

// 下拉选项
const customerOptions = ref([]);
const userOptions = ref([]);
const customerLoading = ref(false);
const searchCustomerKeyword = ref('');
const showCreateOption = ref(false);
const exportLoading = ref(false);

// 计算属性
const isFiltered = computed(() => {
  return Object.values(queryParams).some(value => value) || 
         dateRange.effective_date.length > 0 || 
         dateRange.expiry_date.length > 0;
});

// 初始化
onMounted(async () => {
  loadUsers();
  fetchHostOrderList();
});

// 加载用户列表（对接人）
const loadUsers = async () => {
  try {
    const res = await getUserList();
    userOptions.value = res.data.items || [];
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  }
};

// 客户远程搜索
const remoteCustomerSearch = async (query) => {
  searchCustomerKeyword.value = query;
  
  if (query) {
    customerLoading.value = true;
    try {
      console.log('开始搜索客户:', query);
      const res = await getCustomerList({ customer_name: query });
      console.log('客户搜索原始返回:', res);
      
      // 解析客户数据
      let customers = [];
      
      // 直接检查返回的结构
      if (Array.isArray(res)) {
        customers = res;
      } else if (res && typeof res === 'object') {
        if (Array.isArray(res.results)) {
          customers = res.results;
        } else if (res.data) {
          if (Array.isArray(res.data)) {
            customers = res.data;
          } else if (res.data.results && Array.isArray(res.data.results)) {
            customers = res.data.results;
          }
        }
      }
      
      console.log('处理后的客户数据:', customers);
      
      // 确保每个客户对象有id和customer_name属性
      customerOptions.value = customers.filter(customer => 
        customer && customer.id !== undefined && customer.customer_name
      );
      
      console.log('过滤后的客户选项:', customerOptions.value);
      
      // 始终显示创建新客户的选项，除非已存在相同名称
      showCreateOption.value = query.length > 0 && 
        !customerOptions.value.some(item => 
          item.customer_name.toLowerCase() === query.toLowerCase()
        );
      
      console.log('是否显示创建选项:', showCreateOption.value);
    } catch (error) {
      console.error('搜索客户失败:', error);
      customerOptions.value = [];
      // 出错时也允许创建新客户
      showCreateOption.value = query.length > 0;
    } finally {
      customerLoading.value = false;
    }
  } else {
    // 清空查询时不显示任何选项
    customerOptions.value = [];
    showCreateOption.value = false;
  }
};

// 客户选择变更
const handleCustomerSelectChange = async (value) => {
  console.log('客户选择变更:', value);
  if (value === 'create_new') {
    try {
      console.log('创建新客户:', searchCustomerKeyword.value);
      
      // 确保客户名称不为空
      if (!searchCustomerKeyword.value || searchCustomerKeyword.value.trim() === '') {
        ElMessage.warning('客户名称不能为空');
        hostOrderForm.customer = '';
        return;
      }
      
      // 准备创建客户数据
      const createData = { 
        customer_name: searchCustomerKeyword.value,
        customer_source: hostOrderForm.order_source 
      };
      console.log('创建客户数据:', createData);
      
      // 调用API创建客户
      const res = await createCustomer(createData);
      console.log('创建客户返回:', res);
      
      // 处理返回数据
      let newCustomer = null;
      
      if (res && typeof res === 'object') {
        if (res.data) {
          newCustomer = res.data;
        } else if (res.id && res.customer_name) {
          newCustomer = res;
        }
      }
      
      if (!newCustomer || !newCustomer.id) {
        throw new Error('创建客户成功但返回数据不完整');
      }
      
      ElMessage.success('创建客户成功');
      
      console.log('新创建的客户:', newCustomer);
      
      // 将新客户添加到选项中
      customerOptions.value = [newCustomer, ...customerOptions.value];
      
      // 设置表单的客户ID
      hostOrderForm.customer = newCustomer.id;
      
      // 关闭创建选项
      showCreateOption.value = false;
    } catch (error) {
      console.error('创建客户失败:', error);
      ElMessage.error('创建客户失败: ' + (error.message || '未知错误'));
      hostOrderForm.customer = '';
    }
  }
};

// 获取主机出租订单列表
const fetchHostOrderList = async () => {
  loading.value = true;
  try {
    // 处理日期范围
    const params = { ...queryParams };
    if (dateRange.effective_date && dateRange.effective_date.length === 2) {
      params.effective_date_start = dateRange.effective_date[0];
      params.effective_date_end = dateRange.effective_date[1];
    }
    if (dateRange.expiry_date && dateRange.expiry_date.length === 2) {
      params.expiry_date_start = dateRange.expiry_date[0];
      params.expiry_date_end = dateRange.expiry_date[1];
    }
    
    // 添加分页
    params.page = pagination.page;
    params.page_size = pagination.pageSize;
    
    const res = await getHostOrderList(params);
    hostOrderList.value = res.data.results || [];
    pagination.total = res.data.count || 0;
  } catch (error) {
    console.error('获取主机出租订单列表失败:', error);
    ElMessage.error('获取主机出租订单列表失败');
    hostOrderList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 查询按钮
const handleQuery = () => {
  pagination.page = 1;
  fetchHostOrderList();
};

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    queryParams[key] = '';
  });
  dateRange.effective_date = [];
  dateRange.expiry_date = [];
  pagination.page = 1;
  fetchHostOrderList();
};

// 表格选择项变更
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 分页大小变更
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchHostOrderList();
};

// 当前页变更
const handleCurrentChange = (val) => {
  pagination.page = val;
  fetchHostOrderList();
};

// 添加主机出租订单
const handleAdd = () => {
  dialogType.value = 'add';
  dialogTitle.value = '添加主机出租订单';
  resetForm();
  
  // 加载一些热门客户作为初始选项
  loadRecentCustomers();
  
  dialogVisible.value = true;
};

// 加载最近/热门客户
const loadRecentCustomers = async () => {
  if (customerOptions.value.length > 0) return; // 如果已有选项就不再加载
  
  try {
    customerLoading.value = true;
    console.log('加载热门客户...');
    
    // 不传参数，加载所有客户或者最近的客户
    const res = await getCustomerList({ limit: 10 });
    console.log('热门客户API返回:', res);
    
    // 处理返回数据
    let customers = [];
    
    if (Array.isArray(res)) {
      customers = res;
    } else if (res && typeof res === 'object') {
      if (Array.isArray(res.results)) {
        customers = res.results;
      } else if (res.data) {
        if (Array.isArray(res.data)) {
          customers = res.data;
        } else if (res.data.results && Array.isArray(res.data.results)) {
          customers = res.data.results;
        }
      }
    }
    
    // 确保每个客户对象有id和customer_name属性
    customerOptions.value = customers.filter(customer => 
      customer && customer.id !== undefined && customer.customer_name
    );
    
    console.log('已加载热门客户选项:', customerOptions.value);
  } catch (error) {
    console.error('加载热门客户失败:', error);
  } finally {
    customerLoading.value = false;
  }
};

// 加载指定客户
const loadCustomerById = async (customerId) => {
  if (!customerId) return;
  
  try {
    console.log('加载客户ID:', customerId);
    customerLoading.value = true;
    
    const res = await getCustomer(customerId);
    console.log('获取客户详情返回:', res);
    
    // 处理返回的客户数据
    let customer = null;
    
    if (res && typeof res === 'object') {
      if (res.data) {
        customer = res.data;
      } else if (res.id && res.customer_name) {
        customer = res;
      }
    }
    
    if (!customer || !customer.id) {
      console.error('客户数据不完整:', customer);
      return;
    }
    
    console.log('找到客户:', customer);
    
    // 确保客户选项中包含这个客户
    const exists = customerOptions.value.some(item => item.id === customer.id);
    
    if (!exists) {
      customerOptions.value = [customer, ...customerOptions.value];
      console.log('已添加客户到选项中:', customerOptions.value);
    }
  } catch (error) {
    console.error('加载客户详情失败:', error);
  } finally {
    customerLoading.value = false;
  }
};

// 编辑主机出租订单
const handleEdit = async (row) => {
  dialogTitle.value = '编辑主机出租订单';
  dialogType.value = 'edit';
  resetForm();
  
  try {
    loading.value = true;
    const res = await getHostOrder(row.id);
    console.log('订单详情数据:', res.data);
    
    // 将数据填充到表单
    Object.keys(hostOrderForm).forEach(key => {
      if (res.data[key] !== undefined) {
        hostOrderForm[key] = res.data[key];
      }
    });
    
    // 如果有客户ID，预加载客户信息到选项中
    if (res.data.customer) {
      await loadCustomerById(res.data.customer);
    }
    
    dialogVisible.value = true;
  } catch (error) {
    console.error('获取主机出租订单详情失败:', error);
    ElMessage.error('获取主机出租订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 查看主机出租订单详情
const handleView = async (row) => {
  try {
    loading.value = true;
    const res = await getHostOrder(row.id);
    detailData.value = res.data;
    viewDialogVisible.value = true;
  } catch (error) {
    console.error('获取主机出租订单详情失败:', error);
    ElMessage.error('获取主机出租订单详情失败');
  } finally {
    loading.value = false;
  }
};

// 删除主机出租订单
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除订单 ${row.order_number} 吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await deleteHostOrder(row.id);
      ElMessage.success('删除成功');
      fetchHostOrderList();
    } catch (error) {
      console.error('删除主机出租订单失败:', error);
      ElMessage.error('删除主机出租订单失败');
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 批量删除主机出租订单
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true;
      await batchDeleteHostOrders(selectedIds.value);
      ElMessage.success('批量删除成功');
      fetchHostOrderList();
    } catch (error) {
      console.error('批量删除主机出租订单失败:', error);
      ElMessage.error('批量删除主机出租订单失败');
    } finally {
      loading.value = false;
    }
  }).catch(() => {});
};

// 导出主机出租订单数据
const handleExport = async () => {
  try {
    exportLoading.value = true;
    
    // 显示加载提示
    const loadingInstance = ElMessage({
      message: '正在准备导出数据，请稍候...',
      type: 'info',
      duration: 0 // 持续显示直到手动关闭
    });
    
    // 处理日期范围
    const params = { ...queryParams };
    if (dateRange.effective_date && dateRange.effective_date.length === 2) {
      params.effective_date_start = dateRange.effective_date[0];
      params.effective_date_end = dateRange.effective_date[1];
    }
    if (dateRange.expiry_date && dateRange.expiry_date.length === 2) {
      params.expiry_date_start = dateRange.expiry_date[0];
      params.expiry_date_end = dateRange.expiry_date[1];
    }
    
    const response = await exportHostOrders(params);
    
    // 关闭加载提示
    loadingInstance.close();
    
    // 检查响应类型
    if (!(response instanceof Blob)) {
      console.error('导出返回的不是Blob数据:', response);
      ElMessage.error('导出失败: 服务器返回格式错误');
      return;
    }
    
    // 验证Blob内容是否有效
    if (response.size === 0) {
      ElMessage.error('导出失败: 返回的文件内容为空');
      return;
    }
    
    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `主机出租订单数据_${new Date().toISOString().slice(0,10)}.xlsx`;
    document.body.appendChild(link);
    link.click();
    
    // 延迟移除链接，确保下载开始
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href); // 释放内存
    }, 100);
    
    ElMessage.success('导出成功');
  } catch (error) {
    // 关闭可能存在的加载提示
    ElMessage.closeAll('info');
    
    console.error('导出主机出租订单数据失败:', error);
    
    // 尝试从错误对象中获取更多信息
    let errorMessage = '导出失败';
    if (error.response) {
      if (error.response.data instanceof Blob) {
        try {
          // 尝试从Blob中读取错误信息
          const text = await error.response.data.text();
          const errorData = JSON.parse(text);
          errorMessage = errorData.message || '服务器返回了错误';
        } catch (e) {
          errorMessage = '导出失败: 无法解析服务器错误';
        }
      } else if (error.response.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.response.statusText) {
        errorMessage = `导出失败: ${error.response.statusText}`;
      }
    } else if (error.message) {
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  } finally {
    exportLoading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!hostOrderFormRef.value) return;
  
  // 验证客户是否存在
  if (hostOrderForm.customer && typeof hostOrderForm.customer === 'string' && hostOrderForm.customer === 'create_new') {
    ElMessage.error('请正确选择客户');
    return;
  }
  
  await hostOrderFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        
        // 确保客户ID是数字，避免传递字符串ID
        if (hostOrderForm.customer && !isNaN(hostOrderForm.customer)) {
          hostOrderForm.customer = Number(hostOrderForm.customer);
        }
        
        console.log('提交的表单数据:', hostOrderForm); // 添加调试日志
        
        if (dialogType.value === 'add') {
          await createHostOrder(hostOrderForm);
          ElMessage.success('添加成功');
        } else {
          await updateHostOrder(hostOrderForm.id, hostOrderForm);
          ElMessage.success('更新成功');
        }
        
        dialogVisible.value = false;
        fetchHostOrderList();
      } catch (error) {
        console.error('保存主机出租订单数据失败:', error);
        ElMessage.error('保存失败: ' + (error.message || '未知错误'));
      } finally {
        loading.value = false;
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (hostOrderFormRef.value) {
    hostOrderFormRef.value.resetFields();
  }
  
  Object.keys(hostOrderForm).forEach(key => {
    switch (key) {
      case 'customer':
        hostOrderForm[key] = ''; // 重置客户字段
        break;
      case 'order_source':
        hostOrderForm[key] = 0;
        break;
      case 'rental_years':
        hostOrderForm[key] = 1;
        break;
      case 'effective_date':
        hostOrderForm[key] = new Date().toISOString().slice(0, 10);
        break;
      case 'expiry_date': {
        // 默认设置为一年后
        const oneYearLater = new Date();
        oneYearLater.setFullYear(oneYearLater.getFullYear() + 1);
        hostOrderForm[key] = oneYearLater.toISOString().slice(0, 10);
        break;
      }
      default:
        hostOrderForm[key] = '';
        break;
    }
  });
  
  // 重置客户相关状态
  customerOptions.value = [];
  searchCustomerKeyword.value = '';
  showCreateOption.value = false;
  
  hostOrderForm.id = undefined;
};

// 导入模板弹窗
const handleImportTemplate = () => {
  importDialogVisible.value = true;
};

// 文件选择变更
const handleFileChange = (file) => {
  selectedFile.value = file;
};

// 文件移除
const handleFileRemove = () => {
  selectedFile.value = null;
};

// 文件超出限制
const handleFileExceed = () => {
  ElMessage.warning('只能上传一个文件，且文件大小不能超过 5MB');
};

// 文件上传前验证
const beforeFileUpload = (file) => {
  // 检查文件类型
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel' ||
                  file.name.endsWith('.xlsx') || 
                  file.name.endsWith('.xls');
                  
  // 检查文件大小（限制为5MB）
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isExcel) {
    ElMessage.error('只能上传Excel文件！');
    return false;
  }
  
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过5MB！');
    return false;
  }
  
  return true;
};

// 提交导入
const submitImport = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要导入的文件');
    return;
  }
  
  try {
    importLoading.value = true;
    const formData = new FormData();
    formData.append('file', selectedFile.value.raw, selectedFile.value.name);
    
    // 发送导入请求
    const res = await importRentals(formData);
    console.log('导入响应:', res);
    
    // 处理响应
    if (res.code === 200) {
      // 显示导入成功信息
      const successCount = res.data?.success_count || 0;
      const errorCount = res.data?.error_count || 0;
      
      if (errorCount > 0) {
        // 有错误记录，显示成功导入但有部分错误
        ElMessage({
          message: `成功导入${successCount}条记录，有${errorCount}条记录导入失败`,
          type: 'warning',
          duration: 5000
        });
        
        // 可以考虑显示错误详情
        console.log('导入错误详情:', res.data?.errors);
      } else {
        // 全部成功
        ElMessage.success(`成功导入${successCount}条记录`);
      }
      
      // 关闭导入对话框
      importDialogVisible.value = false;
      
      // 刷新列表
      fetchHostOrderList();
    } else {
      // 导入失败
      ElMessage.error(res.message || '导入失败');
    }
  } catch (error) {
    console.error('导入主机出租订单失败:', error);
    
    // 尝试从错误对象中获取更多信息
    let errorMessage = '导入失败';
    if (error.response && error.response.data) {
      if (error.response.data.message) {
        // 直接使用返回的错误消息
        errorMessage = error.response.data.message;
      } else if (error.response.data.code) {
        // 如果有错误代码但没有消息，使用带错误代码的默认消息
        errorMessage = `导入失败 (错误代码: ${error.response.data.code})`;
      }
    } else if (error.message) {
      // 使用 Error 对象的消息
      errorMessage = error.message;
    }
    
    ElMessage.error(errorMessage);
  } finally {
    importLoading.value = false;
  }
};

// 下载Excel模板 - 改为调用后端API
const downloadExcelTemplate = async () => {
  try {
    // 添加加载提示
    const loadingInstance = ElMessage({
      message: '正在准备模板文件，请稍候...',
      type: 'info',
      duration: 0, // 持续显示直到手动关闭
    });

    const response = await downloadImportTemplate();

    // 关闭加载提示
    loadingInstance.close();

    // 检查响应类型是否为 blob
    if (!(response instanceof Blob)) {
      // 如果后端返回了错误信息（例如JSON），尝试解析并显示
      try {
        // 假设错误信息在 response.data 或直接是 JSON 字符串
        let errorData = response;
        if (response.data) {
            errorData = response.data;
        }
        // 如果是字符串，尝试解析
        if (typeof errorData === 'string') {
            errorData = JSON.parse(errorData);
        }
        ElMessage.error(`下载模板失败: ${errorData.message || '未知后端错误'}`);
      } catch (parseError) {
        console.error("解析后端错误响应失败:", parseError);
        ElMessage.error('下载模板失败：服务器返回了非预期的响应格式。');
      }
      return;
    }

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);

    // 设置下载的文件名，可以尝试从 Content-Disposition 获取，如果后端设置了的话
    // const contentDisposition = response.headers?.['content-disposition'];
    // let filename = '主机出租数据导入模板.xlsx'; // 默认文件名
    // if (contentDisposition) {
    //   const filenameMatch = contentDisposition.match(/filename="?(.+)"?/i);
    //   if (filenameMatch && filenameMatch.length > 1) {
    //     filename = decodeURIComponent(filenameMatch[1]);
    //   }
    // }
    // 暂时还是使用固定文件名
    link.download = '主机出租数据导入模板.xlsx';

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(link.href);

    ElMessage.success('模板文件下载成功');
  } catch (error) {
    // 关闭可能存在的加载提示
    ElMessage.closeAll('info'); // 关闭所有 info 类型的消息

    console.error('下载模板失败:', error);
    // 尝试从 error 对象中获取更详细的信息
    let errorMessage = '下载模板失败，请稍后重试。';
    if (error.response && error.response.data) {
        // 如果响应是 Blob 并且包含错误信息
        if (error.response.data instanceof Blob && error.response.data.type.toLowerCase().includes('json')) {
            try {
                const errorJson = JSON.parse(await error.response.data.text());
                errorMessage = `下载模板失败: ${errorJson.message || '后端返回错误'}`;
            } catch (e) {
                errorMessage = '下载模板失败: 无法解析后端错误信息。';
            }
        } else if (error.response.data.message) {
             errorMessage = `下载模板失败: ${error.response.data.message}`;
        }
    } else if (error.message) {
        errorMessage = `下载模板失败: ${error.message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 复制模板到剪贴板
const copyTemplateToClipboard = () => {
  const templateTable = document.querySelector('.template-table');
  if (templateTable) {
    const range = document.createRange();
    range.selectNodeContents(templateTable);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand('copy');
    selection.removeAllRanges();
    ElMessage.success('模板表格内容已复制到剪贴板');
  }
};
</script>

<style scoped>
.apple-style-container {
  padding: 0 10px 10px 10px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  background-color: #f5f5f7;
  min-height: calc(100vh - 100px);
  max-width: 98%;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.filter-card, .table-card {
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  margin-bottom: 24px;
  background-color: white;
}

.filter-card {
  padding: 16px;
}

.table-card {
  padding: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.left-buttons, .right-buttons {
  display: flex;
  gap: 8px;
}

.apple-button {
  border-radius: 20px;
  height: 40px;
  padding: 0 16px;
  font-size: 14px;
  font-weight: 500;
  border: none;
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.apple-button:hover {
  background: rgba(0, 0, 0, 0.1);
}

.primary-button {
  background: #0071e3;
  color: white;
}

.primary-button:hover {
  background: #0077ed;
  opacity: 0.9;
}

.danger-button {
  background: #ff3b30;
  color: white;
}

.danger-button:hover {
  background: #ff4f45;
  opacity: 0.9;
}

.success-button {
  background: #34c759;
  color: white;
}

.success-button:hover {
  background: #30d158;
  opacity: 0.9;
}

.apple-table {
  border-radius: 12px;
  overflow: hidden;
}

.apple-link-button {
  font-size: 14px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

:deep(.apple-input .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-select .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
}

:deep(.apple-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-select .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-date-picker .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
}

:deep(.apple-date-picker .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-date-picker .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.apple-input-number .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
}

:deep(.apple-input-number .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-input-number .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

:deep(.el-table th.el-table__cell) {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #0071e3;
}

:deep(.apple-dialog .el-dialog__header) {
  padding: 16px 20px;
  margin: 0;
  background: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

:deep(.apple-dialog .el-dialog__footer) {
  padding: 16px 20px;
  margin: 0;
  border-top: 1px solid #e6e6e6;
}

:deep(.apple-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.apple-descriptions .el-descriptions__label) {
  background-color: #f8f8fc;
}

.apple-textarea {
  width: 100%;
}

:deep(.apple-textarea .el-textarea__inner) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #d2d2d7;
  transition: box-shadow 0.3s ease;
}

:deep(.apple-textarea .el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #86868b;
}

:deep(.apple-textarea .el-textarea__inner:focus) {
  box-shadow: 0 0 0 2px #0071e3;
}

/* 客户选择框的特殊样式 */
.customer-select-wrapper {
  position: relative;
  width: 100%;
}

:deep(.el-select-dropdown__item) {
  padding: 8px 12px;
}

:deep(.el-select-dropdown__item.selected) {
  font-weight: bold;
  color: #0071e3;
}

/* 创建新客户选项样式 */
:deep(.el-select-dropdown__item:last-child) {
  border-top: 1px dashed #dcdfe6;
  margin-top: 5px;
  padding-top: 10px;
  color: #67c23a;
  font-weight: bold;
}

/* 高亮客户选中状态 */
:deep(.el-form-item.is-success .el-input__wrapper) {
  box-shadow: 0 0 0 1px #67c23a inset;
}

/* 导入模板弹窗样式 */
.apple-upload {
  margin-top: 16px;
}

/* 上传提示样式 */
.upload-tip {
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f8fc;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
}

.download-template-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  font: inherit;
  cursor: pointer;
  outline: inherit;
  color: #0071e3;
  font-size: 14px;
}

/* 导入模板弹窗样式 */
.import-extra-actions {
  margin-top: 16px;
  text-align: right;
}

.blue-link-btn {
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  font: inherit;
  cursor: pointer;
  outline: inherit;
  color: #0071e3;
  font-size: 14px;
}

.download-icon {
  margin-right: 8px;
}

/* 模板表格样式 */
.template-table-container {
  margin-top: 16px;
  padding: 12px;
  background-color: #f8f8fc;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
}

.template-instruction {
  margin-bottom: 12px;
}

.copy-button-container {
  margin-bottom: 12px;
  text-align: right;
}

.scrollable-table {
  max-height: 200px;
  overflow-y: auto;
}

.template-table {
  width: 100%;
  border-collapse: collapse;
}

.template-table th, .template-table td {
  padding: 8px;
  text-align: left;
}

.template-table th {
  background-color: #f5f7fa;
  font-weight: 600;
  color: #333;
}

.template-notes {
  margin-top: 12px;
  padding: 8px;
  background-color: #f8f8fc;
  border-radius: 8px;
  border: 1px solid #e6e6e6;
}
</style> 